1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
/*!
Evaluation for `isotope` values
*/
#![allow(dead_code)]
use crate::error::*;
use crate::value::*;
use fxhash::FxHashMap as HashMap;
use std::collections::hash_map::Entry;

/// A context for the evaluation of `isotope` values
///
/// May be cheaply (O(1)) cloned, for use in a semi-immutable fashion.
#[derive(Debug, Eq, Default)]
pub struct EvalCtx {
    /// The symbol definition set
    symbols: HashMap<SymbolId, ValId>,
    /// The relative evaluation cache
    cache: HashMap<ValId, ValId>,
    /// Whether this context is normalizing
    normalizing: bool,
}

impl EvalCtx {
    /// Create a new evaluation context
    pub fn new(normalizing: bool) -> EvalCtx {
        EvalCtx {
            normalizing,
            ..EvalCtx::default()
        }
    }
    /// Get the definition of a symbol
    pub fn get(&self, symbol: &SymbolId) -> Option<&ValId> {
        self.symbols.get(symbol)
    }
    /// Check whether this free variable set is modified by this evaluation context
    pub fn is_subst(&self, symbols: &SymbolSet) -> bool {
        self.symbols.keys().any(|symbol| symbols.contains(symbol))
    }
    /// Check whether this free variable set is modified by this evaluation context
    pub fn is_not_subst(&self, symbols: &SymbolSet) -> bool {
        self.symbols.keys().all(|symbol| !symbols.contains(symbol))
    }
    /// Get the cached evaluation for a `ValId`
    pub fn cached_eval(&self, value: &ValId) -> Option<&ValId> {
        self.cache.get(value)
    }
    /// Cache an evaluation
    pub(crate) fn cache_eval(&mut self, value: ValId, eval: ValId) {
        let code = eval.code();
        let old = self.cache.insert(value, eval);
        if let Some(old) = old {
            debug_assert_eq!(old.code(), code)
        }
    }
    /// Flush the cache
    pub fn flush_cache(&mut self) {
        self.cache.clear()
    }
    /// Define a mapping, flushing the cache if any changes were made
    pub(crate) fn def_flush(
        &mut self,
        symbol: SymbolId,
        value: ValId,
    ) -> Result<(Match, bool), Error> {
        let m = symbol.match_symbol(&value)?;
        let change = self.def_flush_unchecked(symbol, value);
        Ok((m, change))
    }
    /// Define a mapping, flushing the cache if any changes were made
    pub(crate) fn def_flush_unchecked(&mut self, symbol: SymbolId, value: ValId) -> bool {
        let symbol_is_value = symbol == value;
        let change = match self.symbols.entry(symbol) {
            Entry::Occupied(mut o) => {
                if *o.get() == value {
                    false
                } else {
                    o.insert(value);
                    true
                }
            }
            Entry::Vacant(v) => {
                if symbol_is_value {
                    false
                } else {
                    v.insert(value);
                    true
                }
            }
        };
        if change {
            self.flush_cache()
        }
        change
    }
    /// Set whether this context is normalizing
    pub fn set_normalizing(&mut self, normalizing: bool) {
        if self.normalizing != normalizing {
            self.normalizing = normalizing;
            self.flush_cache()
        }
    }
    /// Get whether this context is empty
    pub fn is_empty(&self) -> bool {
        self.symbols.is_empty()
    }
    /// Get whether this context is normalizing
    pub fn is_normalizing(&self) -> bool {
        self.normalizing
    }
    /// Get whether this is the null context, i.e. empty and non-normalizing
    pub fn is_null(&self) -> bool {
        self.is_empty() && !self.is_normalizing()
    }
    /// Get this evaluation context, with a symbol added. Return `None` if no changes were made, and return an error on a typing mismatch
    pub fn added(&self, symbol: SymbolId, value: ValId) -> Result<(Match, Option<EvalCtx>), Error> {
        symbol
            .match_symbol(&value)
            .map(|m| (m, self.added_unchecked(symbol, value)))
    }
    /// Get this evaluation context, with a symbol added. Return `None` if no changes were made
    pub(crate) fn added_unchecked(&self, symbol: SymbolId, value: ValId) -> Option<EvalCtx> {
        //TODO: optimize, FIXME
        /*
        #[cfg(debug_assertions)]
        {
            let m = symbol.match_symbol(&value);
            debug_assert!(
                m.is_ok(),
                "Symbol {:#?}: {:#?} failed to match value {:#?}: {:#?}, with match {:?}",
                symbol,
                symbol.ty(),
                value,
                value.ty(),
                m
            );
        }
        */
        if let Some(old_value) = self.symbols.get(&symbol) {
            if *old_value == value {
                return None
            }
        } else if symbol == value {
            return None
        }
        let mut symbols = self.symbols.clone();
        symbols.insert(symbol, value);
        Some(EvalCtx {
            symbols,
            cache: HashMap::default(),
            normalizing: self.normalizing,
        })
    }
    /// Get this evaluation context, with a symbol removed. Return `None` if no changes were made
    pub fn removed(&self, symbol: &SymbolId) -> Option<EvalCtx> {
        //TODO: optimize
        if !self.symbols.contains_key(symbol) {
            return None;
        }
        let mut symbols = self.symbols.clone();
        symbols.remove(symbol);
        Some(EvalCtx {
            symbols,
            cache: HashMap::default(),
            normalizing: self.normalizing,
        })
    }
}

impl PartialEq for EvalCtx {
    fn eq(&self, other: &EvalCtx) -> bool {
        self.normalizing == other.normalizing && self.symbols == other.symbols
    }
}

impl Clone for EvalCtx {
    fn clone(&self) -> EvalCtx {
        // Don't copy the cache, to make cloning cheap
        EvalCtx {
            symbols: self.symbols.clone(),
            cache: HashMap::default(),
            normalizing: self.normalizing,
        }
    }
}